package com.nanshenycd.service.impl;

import com.nanshenycd.dao.IpDao;
import com.nanshenycd.dao.ViewDao;
import com.nanshenycd.pojo.View;
import com.nanshenycd.service.ViewsService;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ViewsServiceImpl implements ViewsService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IpDao ipDao;
    @Autowired
    private ViewDao viewDao;

    private static final Logger logger = LoggerFactory.getLogger(ViewsServiceImpl.class);

    @Override
    public Long findCountById(Long id) {
        String key = "count:" + id;
        boolean hasKey = redisTemplate.hasKey(key);
        long num;
        System.out.println("==================================");
        System.out.println("==================================");
        System.out.println("==================================");
        System.out.println("==================================");
        System.out.println("==================================");
        if (hasKey) {
            //key存在
//            Long aLong = ((Long) redisTemplate.opsForValue().get(key));
            Long aLong=Long.valueOf(redisTemplate.opsForValue().get(key).toString());
            num = redisTemplate.opsForValue().increment(key, aLong);
            View view = viewDao.selectViewsById(id);
            try {
                if (num % 50 == 0) {//redis中每满50次，做一次数据落地
//                    Long h = (Long) redisTemplate.opsForValue().get(key);
                    view.setCount(num);
                    viewDao.updateCount(view);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Long result = Long.valueOf(redisTemplate.opsForValue().get(key).toString());
            return result;
        } else {
            //数据库没数据，添加数据
            View views = viewDao.selectViewsById(id);
            if (views != null) {
                views.setCount(views.getCount() + 1L);
                viewDao.updateCount(views);
            }
            Long count = views.getCount();
            // 写入缓存
            redisTemplate.opsForValue().set(key, count, 50, TimeUnit.SECONDS);
            return count;
        }
    }
}
